/**
 * Created by Administrator on 15-1-7.
 * 系统管理使用
 */
require.config({
    baseUrl:PUBLIC + "/Admin/js/lib"
});
define(function(require){
    var $ = require('jquery');
    require('jquery.form');
    require('tips/msgbox');
    window.$ = window.jQuery = $;
    var c=require('../common');
    require('datetimepicker/datetimepicker');
    var dialog = require('bDialog/dialog');
    require('select');
    window.dialog=dialog;
    require('fileupload/fupload');

    $(function(){

        //下拉框初始化
        $('#attr_sel,#online_sel,#manage_sel,#site_sel,#push_sel').selectbox();

        //模板使用
        $('#temp_sel').selectbox({callback:function(v){
            var selVal = v.attr('v');
            if(selVal == 1){
                var email_title = $.trim($('input[name="email_title"]').val());
                var html = '<dl>';
                html +='<dt><span class="red mr10">*</span><label for="title">标题模版（邮件主题）：</label></dt>';
                html +='<dd>';
                html +='<input id="title" name="title" value="'+email_title+'" class="tb" type="text" />';
                html +='<p>使用“{”和“}”包含变量名,如“{actor}做了{action}”</p>';
                html +='</dd>';
                html +='</dl>';

                $('.email_title').html(html);
            }else{
                $('.email_title').html('');
            }
        }});

        //删除
        $('table .del').off().on('click',function(){
            var id = $(this).data('id');
            if(empty(id)){
                c.error('请选择操作项！',2000);
                return false;
            }

            dialog({title:'温馨提示',height:100,icon:'warning',content:'是否确定删除？',ok:function(){
                $.get(URL+'/del?id='+id,'',function(data){
                    if(data.status==1){
                        c.success(data.info,1000);
                        setTimeout(function(){
                            location.reload();
                        },1500);
                        return true;
                    } else {
                        c.error(data.info,2000);
                        return false;
                    }
                },'json');
            },
                cancel:function(){},
                okVal:'确定',cancelVal:'取消'});
        });

        //更改状态
        $('table .setPass').off().on('click',function(){
            var t = $(this);
            var id = t.data('id');
            var msg = t.html();
            if(empty(id)){
                c.error('请选择操作项！',2000);
                return false;
            }

            dialog({title:'温馨提示',height:100,icon:'warning',content:'是否'+msg+'该数据?',ok:function(){
                $.get(URL+'/setStatus?id='+id,'',function(data){
                    if(data.status==1){
                        c.success(data.info,1000);
                        setTimeout(function(){
                            location.reload();
                        },1500);
                        return true;
                    } else {
                        c.error(data.info,2000);
                        return false;
                    }
                },'json');
            },
                cancel:function(){},
                okVal:'确定',cancelVal:'取消'});
        });

        //表单提交
        $('#detail_form').ajaxForm({
            beforeSubmit:  checkForm,  // pre-submit callback
            success:       complete,  // post-submit callback
            dataType: 'json'
        });

        function checkForm(){
            return true;
        }

        function complete(data){
            if (data.status==1){
                c.success(data.info,1000);
                if(data.data){
                    setTimeout(function(){
                        location.href=data.data;
                    },1500);
                    return true;
                }else{
                    setTimeout(function(){ window.location.reload(); },1000);
                }
            }else{
                c.error(data.info,2000);
                return false;
            }
        }

        //附件配置
        if($('.tag-lists').length) {
            $("#stringinput").keyup(function () {
                stringinput();
            })
            stringinput();
        }

        //输入后处理
        function stringinput(del_keywords) {
            var keywords = $("#stringinput").attr("default").split(',');
            var inp = $("#stringinput").val().split(',');
            var tag_list = '';

            $.each(keywords,function(i,n){
                if(del_keywords!='' && n==del_keywords || n=="") {
                    keywords.splice(i,1);
                }
            });
            $("#stringinput").attr("default",keywords);

            $.each(inp,function(i,n){
                if(n==del_keywords) {
                    inp.splice(i,1);
                } else if(n!="" && $.inArray(n,keywords)==-1) {
                    keywords.push(n);
                }
            });
            $("#stringinput").val(inp);

            $.each(keywords,function(i,n){
                tag_list += "<li class='delStringInput' data-name='"+n+"'><label>" + n + "</label><em>X</em></li>";
            });

            $("input[name=extension]").val(keywords);//附件配置
            $("input[name=keywords]").val(keywords);//短信配置
            $(".taglist").html('').append(tag_list);
        }

        //敏感词删除
        $('.taglist').delegate('.delStringInput','click',function(){
            var keyword = $(this).data('name');
            stringinput(keyword);
        })

        //用户列表
        $('.user_list').off().on('click',function(){
            var id = $(this).data('id');
            if(empty(id)){
                c.error('请选择操作项！',2000);
                return false;
            }

            var d = dialog({title:'用户列表',url:URL+'/user_list?id='+id,end:function(){
            },ok:function(){
                var roleid = $.trim($('#roleid').val());
                var uids = '';

                // 判断是否输入内容
                if(empty(roleid)){
                    c.error('请选择角色！',2000);
                    return false;
                }

                $('input[name="manageid"]:checked').each(function(i){
                    if(0==i){
                        uids = $(this).val();
                    }else{
                        uids += (","+$(this).val());
                    }
                });

                if(empty(uids)){
                    c.error('请选择角色用户！',2000);
                    return false;
                }

                $.post(URL+'/addRoleUser',{roleid:roleid,uid:uids},function(msg){
                    if(msg.status == 1) {
                        c.success(msg.info,1000);
                        d.remove();
                        return true;
                    } else {
                        c.error(msg.info,2000);
                        return false;
                    }
                });
                return false;
            },cancel:function(){},okVal:'保存',cancelVal:'取消'});

        });

        //规则选中与取消
        $('.list [name="permissions"]').click(function(){
            if($(this).attr('checked')){
                $(this).parent('li').next('li').find('ul').find('input').attr('checked',true);
            }else{
                $(this).parent('li').next('li').find('ul').find('input').attr('checked',false);
            }
        });

        /**
         * 获取规则ID
         * @returns {string}
         */
        function getRulesId(){
            var input = $('body').find('input[name="permissions"]:checked');
            var ids = '';
            for(var i=0;i<input.length;i++){
                ids += ids==''?input.eq(i).val():','+input.eq(i).val();
            }
            return ids;
        }

        //授权
        $('.edit_quan').off().on('click',function(){
           var id = $(this).data('id');
            if(empty(id)){
                c.error('请选择操作项！',2000);
                return false;
            }

            var d = dialog({title:'授权列表',url:URL+'/quan?id='+id,end:function(){
                //角色授权
                $('.roleauth [type="checkbox"]').change(function(){
                    if($(this).is(':checked')){
                        $(this).closest('p').next('ul').find('input').prop('checked',true);
                    }else{
                        $(this).closest('p').next('ul').find('input').prop('checked',false);
                    }
                });
            },ok:function(){
                var roleid = $.trim($('#role_id').val());
                var rules_id = getRulesId();

                // 判断是否输入内容
                if(empty(roleid)){
                    c.error('请选择角色！',2000);
                    return false;
                }

                if(empty(rules_id)){
                    c.error('请选择授权节点！',2000);
                    return false;
                }

                $.post(URL+'/updateQuan',{id:roleid,rules_id:rules_id},function(msg){
                    if(msg.status == 1) {
                        c.success(msg.info,1000);
                        d.remove();
                        return true;
                    } else {
                        c.error(msg.info,2000);
                        return false;
                    }
                });
                return false;
            },cancel:function(){},okVal:'保存',cancelVal:'取消'});

        });

        //删除节点
        $('.so_main').delegate('.del_sub_rules','click',function(){
            var t = $(this);
            var id = t.data('id');
            if(empty(id)){
                c.error('请选择操作项！',2000);
                return false
            }

            dialog({title:'温馨提示',height:100,icon:'warning',content:'是否确定删除？',ok:function(){
                $.get(URL+'/delRules?id='+id,'',function(data){
                    if(data.status==1){
                        c.success(data.info,1000);
                        var li = t.closest('li');
                        if(li.siblings().length){
                            li.remove();
                        }else{
                            t.closest('ul').remove();
                        }
                    }else if(data.status == 2){
                        ZENG.msgbox.show(data.info,1,2000);
                        return false;
                    }else {
                        c.error(data.info,2000);
                        return false;
                    }
                },'json');
            },
                cancel:function(){},
                okVal:'确定',cancelVal:'取消'});
        });

        //添加节点
        $('.so_main').delegate('.add_rules','click',function(){
            var t=$(this);
            var id = t.data('id');
            if(empty(id)){
                id = 0;
            }

            var d = dialog({title:'添加规则',width:400,url:URL+'/add?id='+id,end:function(){
                $('#pid_sel').selectbox({w:175});
            },ok:function(){
                var name = $.trim($('input[name="name"]').val());
                var title = $.trim($('input[name="title"]').val());
                var pid = $.trim($('#pid_sel').val());
                var status = $.trim($('input[name="status"]:checked').val());
                var sort = $.trim($('input[name="sort"]').val());

                // 判断是否输入内容
                if(empty(name)){
                    c.error('规则名称不能为空!',2000);
                    $('input[name="name"]').focus();
                    return false;
                }
                if(name.length > 50){
                    c.error('规则名称不能超过50个字符!',2000);
                    $('input[name="name"]').focus();
                    return false;
                }
                if(empty(title)){
                    c.error('显示名称不能为空!',2000);
                    $('input[name="title"]').focus();
                    return false;
                }
                if(title.length > 30){
                    c.error('显示名称不能超过30个字符!',2000);
                    $('input[name="title"]').focus();
                    return false;
                }

                $.post(URL+'/add',{name:name,title:title,status:status,pid:pid,sort:sort},function(msg){
                    if(msg.status == 1) {
                        c.success(msg.info,1000);
                        if(msg.data){
                            if(empty(id)){
                                //主节点
                                $('.tree > ul').append(msg.data);
                            }else{
                                //子节点
                                var ul=t.closest('p').next('ul');
                                if(ul.length==0){
                                    ul=$('<ul></ul>');
                                    t.closest('p').after(ul);
                                }
                                ul.append(msg.data);
                                ul.show();
                            }
                        }
                        d.remove();
                    } else {
                        c.error(msg.info,2000);
                        d.remove();
                        return false;
                    }
                });
                return false;
            },cancel:function(){},okVal:'保存',cancelVal:'取消'});
            return false;
        });

        //编辑节点
        $('.so_main').delegate('.edit_rules','click',function(){
            var t = $(this);
            var id = t.data('id');
            var d = dialog({title:'编辑规则',width:400,url:URL+'/edit?id='+id,end:function(){
                $('#pid_sel').selectbox({w:175});
            },ok:function(){
                var name = $.trim($('input[name="name"]').val());
                var title = $.trim($('input[name="title"]').val());
                var pid = $.trim($('#pid_sel').val());
                var status = $.trim($('input[name="status"]:checked').val());
                var sort = $.trim($('input[name="sort"]').val());

                // 判断是否输入内容
                if(empty(id)){
                    c.error('请选择操作项!',2000);
                    return false;
                }

                if(empty(name)){
                    c.error('规则名称不能为空!',2000);
                    $('input[name="name"]').focus();
                    return false;
                }
                if(name.length > 50){
                    c.error('规则名称不能超过50个字符!',2000);
                    $('input[name="name"]').focus();
                    return false;
                }
                if(empty(title)){
                    c.error('显示名称不能为空!',2000);
                    $('input[name="title"]').focus();
                    return false;
                }
                if(title.length > 30){
                    c.error('显示名称不能超过30个字符!',2000);
                    $('input[name="title"]').focus();
                    return false;
                }

                $.post(URL+'/edit',{name:name,title:title,status:status,pid:pid,sort:sort,id:id},function(msg){
                    if(msg.status == 1) {
                        c.success(msg.info,1000);
                        d.remove();
                        t.closest('p').find('.title').html(title);
                        return true;
                    } else {
                        c.error(msg.info,2000);
                        d.remove();
                        return false;
                    }
                });

                return false;
            },cancel:function(){},okVal:'保存',cancelVal:'取消'});
            return false;
        });

        //添加第三方配置
        $('.so_main').delegate('.add_third','click',function(){
            var d = dialog({title:'添加第三方配置',width:400,url:URL+'/edit',end:function(){

            },ok:function(){
                var title = $.trim($('input[name="title"]').val());
                var app_id = $.trim($('input[name="app_id"]').val());
                var secret = $.trim($('input[name="secret"]').val());

                // 判断是否输入内容
                if(empty(title)){
                    c.error('请输入第三方平台名称!',2000);
                    $('input[name="title"]').focus();
                    return false;
                }
                if(empty(app_id)){
                    c.error('请输入app key!',2000);
                    $('input[name="app_id"]').focus();
                    return false;
                }
                if(empty(secret)){
                    c.error('请输入app_secret!',2000);
                    $('input[name="secret"]').focus();
                    return false;
                }

                $.post(URL+'/update',{title:title,appid:app_id,secret:secret},function(msg){
                    if(msg.status == 1) {
                        c.success(msg.info,1000);
                        setTimeout(function(){
                            location.reload();
                        },1500);
                        return true;
                    } else {
                        c.error(msg.info,2000);
                        d.remove();
                        return false;
                    }
                });

                return false;
            },cancel:function(){},okVal:'保存',cancelVal:'取消'});
        });

        //编辑第三方配置
        $('.so_main').delegate('.edit_third','click',function(){
            var t = $(this);
            var id = t.data('id');
            var d = dialog({title:'第三方配置',width:400,url:URL+'/edit?id='+id,end:function(){

            },ok:function(){
                var title = $.trim($('input[name="title"]').val());
                var app_id = $.trim($('input[name="app_id"]').val());
                var secret = $.trim($('input[name="secret"]').val());

                // 判断是否输入内容
                if(empty(title)){
                    c.error('请输入第三方平台名称!',2000);
                    $('input[name="title"]').focus();
                    return false;
                }
                if(empty(app_id)){
                    c.error('请输入app key!',2000);
                    $('input[name="app_id"]').focus();
                    return false;
                }
                if(empty(secret)){
                    c.error('请输入app_secret!',2000);
                    $('input[name="secret"]').focus();
                    return false;
                }

                $.post(URL+'/update',{title:title,appid:app_id,secret:secret,id:id},function(msg){
                    if(msg.status == 1) {
                        c.success(msg.info,1000);
                        setTimeout(function(){
                            location.reload();
                        },1500);
                        return true;
                    } else {
                        c.error(msg.info,2000);
                        d.remove();
                        return false;
                    }
                });
                return false;
            },cancel:function(){},okVal:'保存',cancelVal:'取消'});
        });

        //重置密码
        $('.resetPassword').off().on('click',function(){
            var id = $(this).data('id');
            if(empty(id)){
                c.error('请选择操作项！',2000);
                return false;
            }

            dialog({title:'温馨提示',height:100,icon:'warning',content:'密码将重置为【123456】，是否重置',ok:function(){
                $.get(URL+'/resetPassword?id='+id,'',function(data){
                    if(data.status==1){
                        c.success(data.info,1000);
                        return true;
                    }else {
                        c.error(data.info,2000);
                        return false;
                    }
                },'json');
            },cancel:function(){},okVal:'确定',cancelVal:'取消'});
        });

        if ($('#fileuploads').length) {
            var path = $('#upload_paths').val();//存储文件夹
            var field = $('#input_fields').val();//表单的name
            var maxNum = $('#maxNums').val();//上传数量
            var role = $('#role').val();//角色
            var uid = $('#uid').val();//角色对应的用户uid
            uid = uid ? uid : 0;
            var icoh = 0;
            if(maxNum > 1){
                icoh = 1;
            }
            $('#fileuploads').fupload({path: path, input: field, max: maxNum,imgType:'big',role:role,uid:uid,icoh:icoh});
        }
    });

    $('.tree img').click(function(){
        if($(this).parent().next().css('display')=='block'){
            $(this).parent().next().slideUp();
            $(this).attr('src',PUBLIC+'/Admin/images/on.png');
        }else{
            $(this).parent().next().slideDown();
            $(this).attr('src',PUBLIC+'/Admin/images/off.png');
        }
    });


    //添加物流
    $('.so_main').delegate('.add_logistics','click',function(){
        var d = dialog({title:'添加物流',width:400,url:URL+'/edit',end:function(){

        },ok:function(){
            var company = $.trim($('input[name="company"]').val());
            var status = $.trim($('input[name="status"]:checked').val());
            var letter = $.trim($('input[name="letter"]').val());

            // 判断是否输入内容
            if(empty(company)){
                c.error('物流名称不能为空!',2000);
                $('input[name="company"]').focus();
                return false;
            }
            if(company.length > 50){
                c.error('物流名称不能超过50个字符!',2000);
                $('input[name="company"]').focus();
                return false;
            }
            if(empty(letter)){
                c.error('物流标示不能为空!',2000);
                $('input[name="letter"]').focus();
                return false;
            }

            $.post(URL+'/update',{company:company,status:status,letter:letter},function(msg){
                if(msg.status == 1) {
                    c.success(msg.info,1000);
                    setTimeout(function(){
                        location.reload();
                    },1500);
                    return true;
                } else {
                    c.error(msg.info,2000);
                    d.remove();
                    return false;
                }
            });

            return false;
        },cancel:function(){},okVal:'保存',cancelVal:'取消'});
    });

    //编辑物流
    $('.so_main').delegate('.edit_logistics','click',function(){
        var t = $(this);
        var id = t.data('id');
        var d = dialog({title:'编辑物流',width:400,url:URL+'/edit?id='+id,end:function(){

        },ok:function(){
            var company = $.trim($('input[name="company"]').val());
            var status = $.trim($('input[name="status"]:checked').val());
            var letter = $.trim($('input[name="letter"]').val());

            // 判断是否输入内容
            if(empty(id)){
                c.error('请选择操作项!',2000);
                return false;
            }

            if(empty(company)){
                c.error('物流名称不能为空!',2000);
                $('input[name="company"]').focus();
                return false;
            }
            if(company.length > 50){
                c.error('物流名称不能超过50个字符!',2000);
                $('input[name="company"]').focus();
                return false;
            }
            if(empty(letter)){
                c.error('物流标示不能为空!',2000);
                $('input[name="letter"]').focus();
                return false;
            }


            $.post(URL+'/update',{company:company,status:status,id:id,letter:letter},function(msg){
                if(msg.status == 1) {
                    c.success(msg.info,1000);
                    setTimeout(function(){
                        location.reload();
                    },1500);
                    return true;
                } else {
                    c.error(msg.info,2000);
                    d.remove();
                    return false;
                }
            });

            return false;
        },cancel:function(){},okVal:'保存',cancelVal:'取消'});

    });


    //客服增加
    $('.addCustom').off().on('click',function(){
        var t = $(this);
        var html = '<div class="custom cf mb10">';
        html +='<input type="text" class="tb tb_200 fl" name="qq[]" value="" />';
        html +='<a href="javascript:;" class="ml10 delCustomer">删除</a>';
        html +='</div>';
        t.before(html);
    });

    $('.cateSet').delegate('.delCustomer','click',function(){
        $(this).parents('.custom').remove();
    })
});